package com.b2c.erp.controller;

import com.b2c.entity.api.ApiResult;
import com.b2c.common.utils.DateUtil;
import com.b2c.common.utils.RandomUtils;
import com.b2c.entity.DataRow;
import com.b2c.entity.result.EnumResultVo;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Request.Builder;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AjaxUploadController {
    @RequestMapping(
            value = {"/ajax/upload_image_base64"},
            method = {RequestMethod.POST}
    )
    public ApiResult<String> uploadImageBase64(@RequestBody DataRow reqData) throws IOException {
        String image = reqData.getString("image");
        String fileName = reqData.getString("fileName");
        if (StringUtils.isEmpty(image)) {
            return new ApiResult(EnumResultVo.ParamsError.getIndex(), "请选择图片");
        } else {
            String pattern = "data:image/(.*);base64,";
            Pattern r = Pattern.compile(pattern);
            Matcher matcher = r.matcher(image);

            String suffix;
            for(suffix = ""; matcher.find(); suffix = matcher.group(1)) {
            }

            if (StringUtils.isEmpty(suffix)) {
                return new ApiResult(EnumResultVo.ParamsError.getIndex(), "请选择图片文件");
            } else {
                Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
                String qiniu_img_domain = properties.getProperty("qiniu_img_domain");
                String qiniu_access_key = properties.getProperty("qiniu_access_key");
                String qiniu_secret_key = properties.getProperty("qiniu_secret_key");
                String qiniu_bucket = properties.getProperty("qiniu_bucket");
                
                String key = RandomUtils.randomString(32);
                if(StringUtils.hasText(fileName)) key = "ecom_goods_img_"+DateUtil.getDateMonth()+"/" + fileName;

                image = image.replace("data:image/" + suffix + ";base64,", "");
                Auth auth = Auth.create(qiniu_access_key, qiniu_secret_key);
                String upToken = auth.uploadToken(qiniu_bucket);
                String upUrl = "https://up.qiniup.com/putb64/-1/key/";//"https://up-z2.qiniup.com/putb64/-1/key/"

                String url = upUrl + UrlSafeBase64.encodeToString(key);

                okhttp3.RequestBody rb = okhttp3.RequestBody.create((MediaType)null, image);
                Request request = (new Builder()).url(url).addHeader("Content-Type", "application/octet-stream").addHeader("Authorization", "UpToken " + upToken).post(rb).build();
                OkHttpClient client = new OkHttpClient();
                Response response = client.newCall(request).execute();
                System.out.println(response.code());
                return response.code() == 200 ? new ApiResult(EnumResultVo.SUCCESS.getIndex(), "成功", qiniu_img_domain + key) : new ApiResult(EnumResultVo.Fail.getIndex(), "失败");
            }
        }
    }
}
